/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rainful;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 *
 * @author Rovers
 */
public class DataAgent implements DataAction {

    private static DataAgent instance;

    private DataAgent() {
    }

    public static DataAgent getInstance() {
        if (instance == null) {
            instance = new DataAgent();
        }
        return instance;
    }

    public void persist(Object data) {
        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {
            pm.makePersistent(data);
        } catch (Exception e) {
            Logger.getLogger(DataAgent.class.getName()).log(Level.SEVERE, null, e);
        } finally {
            pm.close();
        }
    }

    public <T> void persistAll(List<T> datalist) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistentAll(datalist);
        } catch (Exception e) {
            Logger.getLogger(DataAgent.class.getName()).log(Level.SEVERE, null, e);
        } finally {
            pm.close();
        }
    }

    public <T> T selectSingle(Class<T> c, Long id) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            return (T) pm.getObjectById(c, id);
        } catch (Exception e) {
            Logger.getLogger(DataAgent.class.getName()).log(Level.SEVERE, null, e);
            return null;
        } finally {
            pm.close();
        }
    }

    public <T> List<T> select(Class<T> c) {
        return this.select(c, null, null);
    }

    public <T> List<T> select(Class<T> c, String filter, String ordering) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = null;
        try {
            query = pm.newQuery(c);
            if (filter != null) {
                query.setFilter(filter);
            }
            if (ordering != null) {
                query.setOrdering(ordering);
            }

            List<T> result = (List<T>) query.execute();
            pm.detachCopyAll(result);
            return result;

        } catch (Exception e) {
            Logger.getLogger(DataAgent.class.getName()).log(Level.SEVERE, null, e);
            return null;
        } finally {
            if (query != null) {
                query.closeAll();
            }
            pm.close();
        }
    }
}
